from datetime import datetime

from errors import Duplicate, Missing

_client_parkings: list[dict] = []


def create_client_parking_json(
    client_id: int, parking_id: int, time_in: datetime = datetime.now()
) -> dict:
    for client_parking in _client_parkings:
        if (client_parking["client_id"] == client_id) and (
            client_parking["parking_id"] == parking_id
        ):
            raise Duplicate(
                msg=(
                    f"Client client_id={client_id} already "
                    f"parked at parking_id={parking_id}"
                )
            )
    client_parking = {
        "id": len(_client_parkings) + 300,
        "client_id": client_id,
        "parking_id": parking_id,
        "time_in": time_in,
        "time_out": None,
    }
    _client_parkings.append(client_parking)
    return client_parking


def update_client_parking_json(
    client_id: int, parking_id: int, time_out: datetime
) -> dict:
    for client_parking in _client_parkings:
        if (client_parking["client_id"] == client_id) and (
            client_parking["parking_id"] == parking_id
        ):
            client_parking["time_out"] = time_out
            return client_parking
    raise Missing(
        msg=f"ClientParking for client_id={client_id}, parking_id={parking_id} not found"
    )


def delete_client_parking(client_id: int, parking_id: int) -> None:
    for i, client_parking in enumerate(_client_parkings):
        if (client_parking["client_id"] == client_id) and (
            client_parking["parking_id"] == parking_id
        ):
            del _client_parkings[i]
            return None
    raise Missing(
        msg=f"ClientParking for client_id={client_id}, parking_id={parking_id} not found"
    )


def get_client_parkings_list() -> list[dict]:
    return _client_parkings
